package com.bq.gametrade.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.bq.gametrade.HttpLink;
import com.bq.gametrade.R;
import com.bq.gametrade.base.BaseActivity;
import com.bq.gametrade.bean.GamesAccountDetails;
import com.bq.gametrade.bean.GamesListDetails;
import com.bq.gametrade.bean.ResponseBean;
import com.bq.gametrade.bean.UpdateUserInfo;
import com.bq.gametrade.bean.UpdateUserInfoDetails;
import com.bq.gametrade.bean.UserInfoDetails;
import com.bq.gametrade.http.VRHttp;
import com.bq.gametrade.http.VRHttpListener;
import com.bq.gametrade.ui.dialog.LoadingProgressDialog;
import com.bq.gametrade.view.CircleImageView;
import com.bq.gametrade.view.CustomSpinner;
import com.bq.gametrade.view.PayPasswordValidationView;
import com.bq.gametrade.widget.PromptAlertDialog;
import com.bumptech.glide.Glide;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class GameAccountDetailsActivity extends BaseActivity implements View.OnClickListener {

    private ImageView back, ivService;
    private TextView tvTitle;
    private TextView tvAccountBalanceMoney, tvFishStamps;
    private String gameNameId, gameName;
    private CustomSpinner spGamseList;
    private CircleImageView headImage;

    private TextView tvGameName, tvGameAccount, tvMyGameMoney;
    private EditText etTicket;
    private Button btnInto, btnOut;
    private List<GamesListDetails> list = new ArrayList<>();
    private GamesAccountDetails details;
    private LoadingProgressDialog progressDialog;
    private UserInfoDetails userInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gameaccount_details);
        progressDialog = new LoadingProgressDialog(this, "正在支付···");
        if(application.isLogin()){
            userInfo = application.getUserInfo();
        }else {
            startActivity(new Intent(this, LoginActivity.class));
            finish();
        }
        gameNameId = getIntent().getStringExtra("gameNameId");
        gameName = getIntent().getStringExtra("gameName");
        showSpotsDialog();
        gamesAccountDeatils(gameNameId);

        initView();
        setData();
        setViewData();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private void setViewData() {
        Glide.with(GameAccountDetailsActivity.this).load(userInfo.headimg).error(R.mipmap.user_headimg_gray).into(headImage);


    }

    private void initView() {
        back = serchViewById(R.id.image_back);
        back.setOnClickListener(this);
        ivService = serchViewById(R.id.iv_userService);
        ivService.setVisibility(View.GONE);
        tvTitle = serchViewById(R.id.title_name);
        tvTitle.setText("游戏账户信息");
        headImage = serchViewById(R.id.civ_headImage);


        tvAccountBalanceMoney = serchViewById(R.id.account_balanceMoney);
        tvFishStamps = serchViewById(R.id.tv_fishStamps);

        tvGameName = serchViewById(R.id.tv_gameName);
        tvGameAccount = serchViewById(R.id.tv_gameAccount);
        tvMyGameMoney = serchViewById(R.id.tv_gameBalanceMoney);

        etTicket = serchViewById(R.id.et_ticket);
        btnInto = serchViewById(R.id.btn_into);
        btnInto.setOnClickListener(this);
        btnOut = serchViewById(R.id.btn_out);
        btnOut.setOnClickListener(this);

    }


    private void setData() {
        tvAccountBalanceMoney.setText("账户余额：" + userInfo.userMoney + "元");
        tvFishStamps.setText("我的(鱼券)：" + userInfo.userCard);
        tvGameName.setText(gameName);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.image_back:
                finish();
                break;
            case R.id.btn_into:
                /**
                 * type   1平台转到游戏账户
                 */
                if (TextUtils.isEmpty(etTicket.getText().toString())) {
                    toastShow("转入游戏账户鱼券不能为空");
                    return;
                }
                if (Double.parseDouble(etTicket.getText().toString()) > Double.parseDouble(userInfo.userCard)) {
                    toastShow("转入游戏账户鱼券不足");
                    return;
                }
                toPay(1);
                break;
            case R.id.btn_out:
                /**
                 * type 0 转入到平台
                 */
                if (TextUtils.isEmpty(etTicket.getText().toString())) {
                    toastShow("转出鱼券不能为空");
                    return;
                }
                if (tvMyGameMoney.getText().toString().equals("")) {
                    toastShow("游戏账户鱼券不足");
                    return;
                }
                if (Double.parseDouble(etTicket.getText().toString()) > Double.parseDouble(tvMyGameMoney.getText().toString())) {
                    toastShow("转出鱼券不能超过账号上的鱼券");
                    return;
                }
                toPay(0);
                break;

        }
    }


    /**
     * 验证支付密码-----start
     */

    private void toPay(final int type) {
        final PayPasswordValidationView payPasswordValidationView = new PayPasswordValidationView(GameAccountDetailsActivity.this, userInfo, progressDialog);
        payPasswordValidationView.showAtLocation(GameAccountDetailsActivity.this.findViewById(R.id.activity_gameAccountDetails),
                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        payPasswordValidationView.backgroundAlpha(0.6f);
        payPasswordValidationView.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                payPasswordValidationView.backgroundAlpha(1f);
            }
        });

        payPasswordValidationView.setOnFinishInputPayPassword(new PayPasswordValidationView.OnPayPasswordInputFinish() {
            @Override
            public void inputFinish(String status) {
                if (status.equals("0")) {
                    gamesIntoOrOut(type);
                }
            }
        });
    }

    /**
     * end
     **/

    private void closeDialog() {
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
    }

    /**
     * end
     **/
    private void gamesAccountDeatils(String id) {
        Map<String, String> params = new HashMap<>();
        params.put("token", userInfo.token);
        params.put("gameId", id);
        params.put("account", userInfo.account);
        VRHttp.getGameAccountDetails(GameAccountDetailsActivity.this, HttpLink.GAEMESACCOUNT_INFO_URL, params, new VRHttpListener() {
            @Override
            public void onSuccess(Object response, boolean isCache) {
                if (response != null) {
                    details = (GamesAccountDetails) response;
                    if (details.status.equals("0")) {
                        tvGameAccount.setText(details.Account);
                        tvMyGameMoney.setText(details.CardNum);
                    } else {
                        toastShow("获取游戏账户出错，请重新进入");
                    }

                } else {
                    toastShow("获取游戏账户出错，请重新进入");
                    finish();
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();
                closeSpotsDialog();
            }

            @Override
            public void onError(String error) {
                super.onError(error);
                toastShow("获取游戏账户出错，请重新进入");
                finish();
            }
        });

    }

    /**
     * type 0 转入到平台   1充值游戏
     */
    private void gamesIntoOrOut(final int type) {
        Map<String, String> params = new HashMap<>();
        params.put("token", userInfo.token);
        params.put("gameId", gameNameId);
        params.put("account", userInfo.account);
        params.put("ticket", etTicket.getText().toString());
        params.put("type", String.valueOf(type));
        VRHttp.sendRequest(GameAccountDetailsActivity.this, HttpLink.GAEMESACCOUNT_RECHARGE_URL, params, new VRHttpListener() {
            @Override
            public void onSuccess(Object response, boolean isCache) {
                if (response != null) {
                    ResponseBean bean = (ResponseBean) response;
                    if (bean.status.equals("0")) {
                        if (type == 1) {
                            toastShow("成功转入" + etTicket.getText().toString() + "鱼券");
                        } else {
                            toastShow("成功转出" + etTicket.getText().toString() + "鱼券");
                        }
                        gamesAccountDeatils(gameNameId);
                        getUserInfo();
                    } else if (bean.status.equals("1")) {
                        toastShow("发送失败！请重试");
                    }else if (bean.status.equals("2")) {
                        new PromptAlertDialog(GameAccountDetailsActivity.this).builder().setTitle("提示").setTouchOutsideCanceled(false)
                                .setMsg("您还没有绑定银行卡不能提现？现在去绑定")
                                .setPositiveButton("绑定", new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        startActivity(new Intent(GameAccountDetailsActivity.this, BankCardAddActivity.class));
                                    }
                                }).setNegativeButton("取消", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                finish();
                            }
                        }).show();
                    } else if (bean.status.equals("99")) {
                        toastShow("登录超时，请登录之后不再试");
                        application.setUserInfo(null);
                        startActivity(new Intent(GameAccountDetailsActivity.this, LoginActivity.class));
                        finish();
                    } else if (bean.status.equals("98")) {
                        toastShow("您的账户已在其他设备登录，请重新登陆");
                        application.setUserInfo(null);
                        startActivity(new Intent(GameAccountDetailsActivity.this, LoginActivity.class));
                        finish();
                    }else {
                        toastShow("转账失败");
                    }

                }
            }

            @Override
            public void onError(String error) {
                super.onError(error);
                if (type == 0) {
                    toastShow("转入游戏账户失败");
                } else {
                    toastShow("从游戏账户转出失败");
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();
                closeDialog();
            }
        });

    }

    private void getUserInfo() {
        Map<String, String> params = new HashMap<>();
        params.put("token", userInfo.token);
        VRHttp.updateUserInfo(GameAccountDetailsActivity.this, HttpLink.GET_USERINFO_URL, params, new VRHttpListener() {
            @Override
            public void onSuccess(Object response, boolean isCache) {
                closeSpotsDialog();
                UpdateUserInfo userInfo = (UpdateUserInfo) response;
                if (userInfo.status.equals("0")) {
                    UpdateUserInfoDetails userInfoDetails = userInfo.userinfo;
                    application.getUserInfo().userCard = userInfoDetails.userCard;
                    tvFishStamps.setText("我的(鱼券)：" + userInfoDetails.userCard);
                } else {
                    toastShow("登录超时请重新登陆");
                    application.setUserInfo(null);
                    startActivity(new Intent(GameAccountDetailsActivity.this, LoginActivity.class));
                }


            }

            @Override
            public void onFinish() {
                super.onFinish();
                closeSpotsDialog();
            }
        });
    }


}
